<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <Header />
    <!-- 左侧导航栏 -->
    <aside
      class="fixed left-0 top-16 bottom-0 w-64 bg-gray-800 text-white z-10 overflow-y-auto"
    >
      <nav class="py-4">
        <div v-for="(menu, index) in mainMenus" :key="index" class="mb-1">
          <div
            class="flex items-center px-6 py-3 cursor-pointer hover:bg-gray-700"
            :class="{ 'bg-blue-700': menu.active }"
            @click="toggleMenu(index)"
          >
            <i :class="menu.icon + ' mr-3 w-5 text-center'"></i>
            <span>{{ menu.name }}</span>
            <i
              class="fas fa-chevron-down ml-auto text-xs transition-transform duration-200"
              :class="{ 'transform rotate-180': menu.expanded }"
            ></i>
          </div>
          <div v-if="menu.expanded" class="bg-gray-900">
            <div
              v-for="(submenu, subIndex) in menu.subMenus"
              :key="subIndex"
              class="flex items-center px-10 py-2 cursor-pointer hover:bg-gray-700"
              :class="{ 'text-blue-400': submenu.active }"
              @click="selectSubmenu(index, subIndex)"
            >
              <a
                v-if="submenu.link"
                :href="submenu.link"
                data-readdy="true"
                class="text-sm w-full"
                >{{ submenu.name }}</a
              >
              <span v-else class="text-sm">{{ submenu.name }}</span>
            </div>
          </div>
        </div>
      </nav>
    </aside>
    <!-- 主内容区域 -->
    <main class="pt-16 pl-64">
      <div class="container mx-auto p-6">
        <!-- 面包屑导航 -->
        <div class="flex items-center text-sm mb-4 text-gray-500">
          <span>首页</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <span>综合分析</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <span class="text-blue-600">应用情况分析</span>
        </div>
        <!-- 筛选条件区域 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex flex-wrap items-center gap-4">
            <div class="flex items-center">
              <span class="text-gray-600 mr-2">企业选择：</span>
              <div class="relative">
                <button
                  class="flex items-center justify-between w-48 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg focus:outline-none !rounded-button whitespace-nowrap cursor-pointer"
                  @click="toggleEnterpriseDropdown"
                >
                  <span class="text-gray-700">{{ selectedEnterprise }}</span>
                  <i class="fas fa-chevron-down text-gray-500 text-xs"></i>
                </button>
                <!-- 企业选择下拉菜单 -->
                <div
                  v-if="showEnterpriseDropdown"
                  class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"
                  @click.stop="preventClose"
                >
                  <div
                    v-for="(enterprise, index) in enterpriseOptions"
                    :key="index"
                    class="px-3 py-2 cursor-pointer hover:bg-gray-100 text-sm transition-colors duration-150"
                    :class="{
                      'bg-blue-50 text-blue-600':
                        selectedEnterprise === enterprise,
                    }"
                    @click="selectEnterprise(enterprise)"
                  >
                    {{ enterprise }}
                  </div>
                </div>
              </div>
            </div>
            <div class="flex items-center">
              <span class="text-gray-600 mr-2">时间范围：</span>
              <div class="flex items-center">
                <input
                  type="date"
                  v-model="startDate"
                  class="w-32 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
                />
                <span class="mx-2 text-gray-500">至</span>
                <input
                  type="date"
                  v-model="endDate"
                  class="w-32 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
                />
              </div>
            </div>
            <div class="ml-auto flex gap-2">
              <button
                class="px-4 py-2 bg-blue-600 text-white rounded-lg flex items-center !rounded-button whitespace-nowrap cursor-pointer"
                @click="applyFilters"
              >
                <i class="fas fa-search mr-1"></i> 查询
              </button>
              <button
                class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg flex items-center !rounded-button whitespace-nowrap cursor-pointer"
                @click="resetFilters"
              >
                <i class="fas fa-refresh mr-1"></i> 重置
              </button>
            </div>
          </div>
        </div>
        <!-- 核心指标概览 -->
        <div class="grid grid-cols-4 gap-4 mb-6">
          <!-- 平台访问量卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 mr-4"
            >
              <i class="fas fa-chart-line text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">平台访问量</div>
              <div class="text-2xl font-bold text-gray-900">2,846</div>
              <div class="text-xs text-green-600 flex items-center">
                <i class="fas fa-arrow-up mr-1"></i> 环比增长 12.5%
              </div>
            </div>
          </div>
          <!-- 活跃用户数卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center text-green-600 mr-4"
            >
              <i class="fas fa-users text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">活跃用户数</div>
              <div class="text-2xl font-bold text-gray-900">1,258</div>
              <div class="text-xs text-gray-600 flex items-center">
                <span class="text-green-600">当前在线: 342</span>
                <span class="mx-1">|</span>
                <span class="text-blue-600">总用户: 1,865</span>
              </div>
            </div>
          </div>
          <!-- 功能使用率卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 mr-4"
            >
              <i class="fas fa-tasks text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">功能使用率</div>
              <div class="text-2xl font-bold text-gray-900">78.6%</div>
              <div class="text-xs text-purple-600 flex items-center">
                <i class="fas fa-star mr-1"></i> TOP5 功能占比
              </div>
            </div>
          </div>
          <!-- 数据上报率卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 mr-4"
            >
              <i class="fas fa-upload text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">数据上报率</div>
              <div class="text-2xl font-bold text-gray-900">94.2%</div>
              <div class="text-xs text-indigo-600 flex items-center">
                <i class="fas fa-certificate mr-1"></i> 数据质量评分: 86
              </div>
            </div>
          </div>
        </div>
        <!-- 应用趋势分析 -->
        <div class="grid grid-cols-2 gap-6 mb-6">
          <!-- 平台使用趋势图 -->
          <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">平台使用趋势</h2>
              <div class="flex space-x-2">
                <button
                  class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                  :class="
                    currentPeriod === 'week'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700'
                  "
                  @click="changePeriod('week')"
                >
                  周
                </button>
                <button
                  class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                  :class="
                    currentPeriod === 'month'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700'
                  "
                  @click="changePeriod('month')"
                >
                  月
                </button>
                <button
                  class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                  :class="
                    currentPeriod === 'year'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700'
                  "
                  @click="changePeriod('year')"
                >
                  年
                </button>
              </div>
            </div>
            <div id="usageTrendChart" class="h-80" ref="usageTrendChart"></div>
          </div>
          <!-- 功能使用分布 -->
          <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">功能使用分布</h2>
              <div class="text-xs text-gray-500">
                <i class="fas fa-sync-alt mr-1"></i> 更新于 {{ currentTime }}
              </div>
            </div>
            <div
              id="functionUsageChart"
              class="h-80"
              ref="functionUsageChart"
            ></div>
          </div>
        </div>
        <!-- 用户活跃度分析 -->
        <div class="grid grid-cols-3 gap-6 mb-6">
          <!-- 用户活跃度热力图 -->
          <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">用户活跃度热力图</h2>
              <div class="text-xs text-gray-500">
                <span class="text-blue-600 font-medium">{{
                  activeUserCount
                }}</span>
                活跃用户
              </div>
            </div>
            <div
              id="userActivityHeatmap"
              class="h-80"
              ref="userActivityHeatmap"
            ></div>
          </div>
          <!-- 用户行为分析 -->
          <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">用户行为分析</h2>
              <div class="text-xs text-gray-500">
                <span class="text-green-600 font-medium">{{
                  totalUserActions
                }}</span>
                次操作
              </div>
            </div>
            <div
              id="userBehaviorChart"
              class="h-80"
              ref="userBehaviorChart"
            ></div>
          </div>
          <!-- 平均使用时长 -->
          <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">平均使用时长</h2>
              <div class="text-xs text-gray-500">
                日均:
                <span class="text-blue-600 font-medium">{{
                  avgUsageTime
                }}</span>
                分钟/用户
              </div>
            </div>
            <div
              id="avgUsageTimeChart"
              class="h-80"
              ref="avgUsageTimeChart"
            ></div>
          </div>
        </div>
        <!-- 企业应用对比 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="font-bold text-lg text-gray-800">企业应用对比</h2>
            <div class="flex space-x-2">
              <button
                class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                :class="
                  currentCompanyPeriod === 'month'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 text-gray-700'
                "
                @click="changeCompanyPeriod('month')"
              >
                本月
              </button>
              <button
                class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                :class="
                  currentCompanyPeriod === 'quarter'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 text-gray-700'
                "
                @click="changeCompanyPeriod('quarter')"
              >
                本季度
              </button>
              <button
                class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                :class="
                  currentCompanyPeriod === 'year'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 text-gray-700'
                "
                @click="changeCompanyPeriod('year')"
              >
                本年度
              </button>
            </div>
          </div>
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead>
                <tr>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    企业名称
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                  >
                    用户数量
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                  >
                    访问频率
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    功能覆盖率
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    数据上报率
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    应用评分
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    操作
                  </th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr
                  v-for="(company, index) in companyUsageData"
                  :key="index"
                  class="hover:bg-gray-50"
                >
                  <td class="px-4 py-3">
                    <div class="flex items-center justify-center">
                      <div
                        class="w-8 h-8 rounded-full flex items-center justify-center mr-3"
                        :class="company.iconBg"
                      >
                        <i :class="company.icon + ' ' + company.iconColor"></i>
                      </div>
                      <div>
                        <div class="text-sm font-medium text-gray-900">
                          {{ company.name }}
                        </div>
                        <div class="text-xs text-gray-500">
                          ID: {{ company.id }}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ company.userCount }}
                    </div>
                    <div class="text-xs text-gray-500">
                      活跃: {{ company.activeUsers }}
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ company.visitFrequency }}
                    </div>
                    <div class="text-xs text-gray-500">
                      {{ company.visitChange }}
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ company.functionCoverage }}
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-1.5">
                      <div
                        class="h-1.5 rounded-full"
                        :style="{
                          width: company.functionCoverageValue + '%',
                          backgroundColor: company.functionCoverageColor,
                        }"
                      ></div>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ company.dataReportRate }}
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-1.5">
                      <div
                        class="h-1.5 rounded-full"
                        :style="{
                          width: company.dataReportRateValue + '%',
                          backgroundColor: company.dataReportRateColor,
                        }"
                      ></div>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="flex items-center justify-center">
                      <div
                        class="text-sm font-medium"
                        :class="company.scoreColor"
                      >
                        {{ company.score }}
                      </div>
                      <div class="ml-2 w-16 bg-gray-200 rounded-full h-1.5">
                        <div
                          class="h-1.5 rounded-full"
                          :style="{
                            width: company.scorePercentage + '%',
                            backgroundColor: company.scoreColor.replace(
                              'text-',
                              'bg-'
                            ),
                          }"
                        ></div>
                      </div>
                    </div>
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                    <div class="flex space-x-2 justify-center">
                      <button
                        class="text-blue-600 hover:text-blue-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="showCompanyDetail(company)"
                      >
                        详情
                      </button>
                      <button
                        class="text-green-600 hover:text-green-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="analyzeCompany(company)"
                      >
                        分析
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <!-- 数据上报分析 -->
        <div class="grid grid-cols-2 gap-6 mb-6">
          <!-- 数据上报达标率趋势 -->
          <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">
                数据上报达标率趋势
              </h2>
              <div class="flex space-x-2">
                <button
                  class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                  :class="
                    currentDataReportPeriod === 'week'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700'
                  "
                  @click="changeDataReportPeriod('week')"
                >
                  周
                </button>
                <button
                  class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                  :class="
                    currentDataReportPeriod === 'month'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700'
                  "
                  @click="changeDataReportPeriod('month')"
                >
                  月
                </button>
                <button
                  class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                  :class="
                    currentDataReportPeriod === 'year'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700'
                  "
                  @click="changeDataReportPeriod('year')"
                >
                  年
                </button>
              </div>
            </div>
            <div
              id="dataReportRateChart"
              class="h-80"
              ref="dataReportRateChart"
            ></div>
          </div>
          <!-- 数据质量分布 -->
          <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="font-bold text-lg text-gray-800">数据质量分布</h2>
              <div class="text-xs text-gray-500">
                <i class="fas fa-sync-alt mr-1"></i> 更新于 {{ currentTime }}
              </div>
            </div>
            <div
              id="dataQualityChart"
              class="h-80"
              ref="dataQualityChart"
            ></div>
          </div>
        </div>
        <!-- 功能使用详情 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="font-bold text-lg text-gray-800">功能使用详情</h2>
          </div>
          <div class="grid grid-cols-3 gap-6">
            <div
              v-for="(feature, index) in featureUsageDetails"
              :key="index"
              class="bg-gray-50 p-4 rounded-lg"
            >
              <div class="flex items-center mb-3">
                <div
                  class="w-10 h-10 rounded-full flex items-center justify-center mr-3"
                  :class="feature.iconBg"
                >
                  <i :class="feature.icon + ' ' + feature.iconColor"></i>
                </div>
                <div>
                  <div class="text-sm font-medium text-gray-900">
                    {{ feature.name }}
                  </div>
                  <div class="text-xs text-gray-500">
                    {{ feature.description }}
                  </div>
                </div>
              </div>
              <div class="mb-2">
                <div class="flex justify-between items-center mb-1">
                  <span class="text-xs text-gray-500">使用频率</span>
                  <span
                    class="text-xs font-medium"
                    :class="feature.usageColor"
                    >{{ feature.usageRate }}</span
                  >
                </div>
                <div class="w-full bg-gray-200 rounded-full h-1.5">
                  <div
                    class="h-1.5 rounded-full"
                    :style="{
                      width: feature.usagePercentage + '%',
                      backgroundColor: feature.usageBarColor,
                    }"
                  ></div>
                </div>
              </div>
              <div class="mb-2">
                <div class="flex justify-between items-center mb-1">
                  <span class="text-xs text-gray-500">用户覆盖率</span>
                  <span
                    class="text-xs font-medium"
                    :class="feature.coverageColor"
                    >{{ feature.userCoverage }}</span
                  >
                </div>
                <div class="w-full bg-gray-200 rounded-full h-1.5">
                  <div
                    class="h-1.5 rounded-full"
                    :style="{
                      width: feature.coveragePercentage + '%',
                      backgroundColor: feature.coverageBarColor,
                    }"
                  ></div>
                </div>
              </div>
              <div class="text-xs text-gray-500 mt-3">
                <span>平均使用时长: </span>
                <span class="font-medium text-blue-600">{{
                  feature.avgUsageTime
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>
<script>
import * as echarts from "echarts";
import Header from "../components/Header.vue";
import { ElMessageBox, ElMessage } from 'element-plus';

export default {
  components: {
    Header,
  },
  data() {
    return {
      currentTime: "2025-07-08 15:32:45",
      // 添加筛选条件相关数据
      showEnterpriseDropdown: false,
      selectedEnterprise: "全部企业",
      startDate: "",
      endDate: "",
      // 企业选项
      enterpriseOptions: [
        "全部企业",
        "河钢集团",
        "宝钢集团",
        "首钢集团",
        "鞍钢集团",
        "武钢集团",
        "马钢集团",
      ],
      mainMenus: [
        {
          name: "监测报警",
          icon: "fas fa-bell",
          expanded: false,
          active: false,
          subMenus: [
            { name: "数据汇聚功能", active: false, link: "/data-aggregation" },
            {
              name: "监测指标统计",
              active: false,
              link: "/monitoring-indicators",
            },
            { name: "区域化展示", active: false, link: "/regional-display" },
          ],
        },
        {
          name: "风险研判",
          icon: "fas fa-exclamation-triangle",
          expanded: false,
          active: false,
          subMenus: [
             { name: '智能风险评估', active: false, link: '/intelligent-risk-assessment' },
                        { name: '预警信息推送', active: false, link: '/risk-warning-push' },
                        { name: '风险管理与分析', active: true, link: '/risk-analysis' },
                    ]
        },
        {
          name: "在线巡查",
          icon: "fas fa-search",
          expanded: false,
          active: false,
          subMenus: [
            {
              name: "企业信息汇总",
              active: false,
              link: "/summary-information",
            },
            { name: "巡查功能", active: false, link: "/patrol" },
            { name: "检索功能", active: false, link: "search" },
            { name: "一屏汇聚展示", active: false, link: "/screen-display" },
          ],
        },
        {
          name: "综合分析",
          icon: "fas fa-chart-line",
          expanded: true,
          active: true,
          subMenus: [
            { name: "联网与设备分析", active: false, link: "/equipment" },
            { name: "应用情况分析", active: true, link: "/application" },
            { name: "数据质量分析", active: false, link: "/data-quality" },
            { name: "定期专题报告", active: false, link: "report" },
          ],
        },
        {
          name: "系统管理",
          icon: "fas fa-cog",
          expanded: false,
          active: false,
          subMenus: [
            { name: "用户权限管理", active: false, link: "user-permission" },
            { name: "系统配置管理", active: false, link: "system-manage" },
            { name: "数据管理", active: false, link: "data-manage" },
            { name: "系统监控与维护", active: false, link: "monitoring" },
          ],
        },
      ],
      currentPeriod: "month",
      currentDataReportPeriod: "month",
      currentCompanyPeriod: "month",
      activeUserCount: 1258,
      totalUserActions: 15632,
      avgUsageTime: 42.8,
      usageTrendChart: null,
      dataReportRateChart: null,
      featureUsageDetails: [
        {
          name: "实时监测",
          description: "设备状态实时监控",
          icon: "fas fa-desktop",
          iconBg: "bg-blue-100",
          iconColor: "text-blue-600",
          usageRate: "92%",
          usagePercentage: 92,
          usageColor: "text-green-600",
          usageBarColor: "#48bb78",
          userCoverage: "88%",
          coveragePercentage: 88,
          coverageColor: "text-green-600",
          coverageBarColor: "#48bb78",
          avgUsageTime: "26 分钟/日",
        },
        {
          name: "风险预警",
          description: "安全风险智能预警",
          icon: "fas fa-exclamation-triangle",
          iconBg: "bg-red-100",
          iconColor: "text-red-600",
          usageRate: "86%",
          usagePercentage: 86,
          usageColor: "text-green-600",
          usageBarColor: "#48bb78",
          userCoverage: "82%",
          coveragePercentage: 82,
          coverageColor: "text-blue-600",
          coverageBarColor: "#4299e1",
          avgUsageTime: "18 分钟/日",
        },
        {
          name: "数据分析",
          description: "生产数据统计分析",
          icon: "fas fa-chart-bar",
          iconBg: "bg-green-100",
          iconColor: "text-green-600",
          usageRate: "78%",
          usagePercentage: 78,
          usageColor: "text-blue-600",
          usageBarColor: "#4299e1",
          userCoverage: "76%",
          coveragePercentage: 76,
          coverageColor: "text-blue-600",
          coverageBarColor: "#4299e1",
          avgUsageTime: "32 分钟/日",
        },
        {
          name: "巡检管理",
          description: "设备巡检任务管理",
          icon: "fas fa-clipboard-check",
          iconBg: "bg-purple-100",
          iconColor: "text-purple-600",
          usageRate: "72%",
          usagePercentage: 72,
          usageColor: "text-blue-600",
          usageBarColor: "#4299e1",
          userCoverage: "68%",
          coveragePercentage: 68,
          coverageColor: "text-yellow-600",
          coverageBarColor: "#ecc94b",
          avgUsageTime: "24 分钟/日",
        },
        {
          name: "报表生成",
          description: "自动生成分析报表",
          icon: "fas fa-file-alt",
          iconBg: "bg-yellow-100",
          iconColor: "text-yellow-600",
          usageRate: "65%",
          usagePercentage: 65,
          usageColor: "text-yellow-600",
          usageBarColor: "#ecc94b",
          userCoverage: "62%",
          coveragePercentage: 62,
          coverageColor: "text-yellow-600",
          coverageBarColor: "#ecc94b",
          avgUsageTime: "15 分钟/日",
        },
        {
          name: "故障处理",
          description: "设备故障处理流程",
          icon: "fas fa-tools",
          iconBg: "bg-orange-100",
          iconColor: "text-orange-600",
          usageRate: "58%",
          usagePercentage: 58,
          usageColor: "text-yellow-600",
          usageBarColor: "#ecc94b",
          userCoverage: "54%",
          coveragePercentage: 54,
          coverageColor: "text-yellow-600",
          coverageBarColor: "#ecc94b",
          avgUsageTime: "22 分钟/日",
        },
      ],
    };
  },
  mounted() {
    this.initUsageTrendChart();
    this.initFunctionUsageChart();
    this.initUserActivityHeatmap();
    this.initUserBehaviorChart();
    this.initAvgUsageTimeChart();
    this.initDataReportRateChart();
    this.initDataQualityChart();
    // 初始化企业应用对比数据
    this.updateCompanyUsageData();
    // 响应窗口大小变化
    window.addEventListener("resize", this.handleResize);
    // 点击其他地方关闭下拉菜单
    document.addEventListener("click", this.closeDropdowns);
    // 更新时间
    this.updateCurrentTime();
    setInterval(this.updateCurrentTime, 1000);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    document.removeEventListener("click", this.closeDropdowns);
    clearInterval(this.timeInterval);
  },
  methods: {
    toggleMenu(index) {
      this.mainMenus[index].expanded = !this.mainMenus[index].expanded;
      // 如果展开了菜单，则将其他菜单收起
      if (this.mainMenus[index].expanded) {
        this.mainMenus.forEach((menu, i) => {
          if (i !== index) {
            menu.expanded = false;
          }
        });
      }
    },
    // 添加筛选相关方法
    toggleEnterpriseDropdown() {
      this.showEnterpriseDropdown = !this.showEnterpriseDropdown;
    },
    selectEnterprise(enterprise) {
      this.selectedEnterprise = enterprise;
      this.showEnterpriseDropdown = false;
    },
    applyFilters() {
      // 验证日期范围
      if (this.startDate && this.endDate && this.startDate > this.endDate) {
        ElMessage.warning("开始日期不能晚于结束日期");
        return;
      }

      

      // 更新核心指标数据
      this.updateCoreMetrics();

      // 根据筛选条件更新所有图表和数据
      this.updateAllChartData();
      this.updateCompanyUsageData();

      // 关闭下拉菜单
      this.showEnterpriseDropdown = false;

      // 成功提示
      ElMessage.success('筛选条件已应用');
    },
    // 更新核心指标数据
    updateCoreMetrics() {
      // 基础指标数据
      const baseMetrics = {
        platformVisits: 2846,
        activeUsers: 1258,
        functionUsageRate: 78.6,
        dataReportRate: 94.2,
      };

      // 根据企业筛选调整数据
      let adjustmentFactor = 1;
      if (this.selectedEnterprise !== "全部企业") {
        adjustmentFactor = this.getEnterpriseScaleFactor(
          this.selectedEnterprise
        );
      }

      // 根据日期范围调整数据
      if (this.startDate || this.endDate) {
        const dateAdjustment = this.calculateDateAdjustment();
        adjustmentFactor *= dateAdjustment;
      }

      // 更新核心指标
      this.activeUserCount = Math.round(
        baseMetrics.activeUsers * adjustmentFactor
      );
      this.totalUserActions = Math.round(15632 * adjustmentFactor);
      this.avgUsageTime = Math.round(42.8 * adjustmentFactor * 10) / 10;

      // 更新卡片显示数据（在实际应用中应该更新对应的数据绑定）
      
    },
    resetFilters() {
      // 重置筛选条件
      this.selectedEnterprise = "全部企业";
      this.startDate = "";
      this.endDate = "";
      this.showEnterpriseDropdown = false;

      // 重置核心指标
      this.activeUserCount = 1258;
      this.totalUserActions = 15632;
      this.avgUsageTime = 42.8;

      // 重置后重新加载所有数据
      this.updateAllChartData();
      this.updateCompanyUsageData();

      // 成功提示
      ElMessage.success('筛选条件已重置');
    },
    // 更新所有图表数据
    updateAllChartData() {
      this.updateUsageTrendChartData();
      this.updateFunctionUsageChartData();
      this.updateUserActivityHeatmapData();
      this.updateUserBehaviorChartData();
      this.updateAvgUsageTimeChartData();
      this.updateDataReportRateChartData();
      this.updateDataQualityChartData();
    },
    // 根据筛选条件过滤企业数据
    filterCompanyData(originalData) {
      let filteredData = [...originalData];

      // 企业筛选
      if (this.selectedEnterprise !== "全部企业") {
        filteredData = filteredData.filter(
          (company) => company.name === this.selectedEnterprise
        );
      }

      // 日期范围筛选（这里可以根据实际业务需求实现更复杂的逻辑）
      if (this.startDate || this.endDate) {
        // 在实际应用中，这里应该根据日期范围过滤数据
        // 由于示例数据是静态的，这里只做简单处理
        
      }

      return filteredData;
    },
    selectSubmenu(menuIndex, submenuIndex) {
      // 重置所有菜单的激活状态
      this.mainMenus.forEach((menu) => {
        menu.active = false;
        menu.subMenus.forEach((submenu) => {
          submenu.active = false;
        });
      });
      // 设置当前选中的菜单和子菜单为激活状态
      this.mainMenus[menuIndex].active = true;
      this.mainMenus[menuIndex].subMenus[submenuIndex].active = true;
    },
    updateCurrentTime() {
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleResize() {
      // 获取所有图表实例并调整大小
      const chartRefs = [
        this.$refs.usageTrendChart,
        this.$refs.functionUsageChart,
        this.$refs.userActivityHeatmap,
        this.$refs.userBehaviorChart,
        this.$refs.avgUsageTimeChart,
        this.$refs.dataReportRateChart,
        this.$refs.dataQualityChart,
      ];
      chartRefs.forEach((ref) => {
        if (ref) {
          const chart = echarts.getInstanceByDom(ref);
          if (chart) {
            chart.resize();
          }
        }
      });
    },
    // 添加关闭下拉菜单的方法
    closeDropdowns(event) {
  // 直接检查点击目标是否在企业选择按钮或下拉菜单内
  const target = event.target;
  const isEnterpriseButton = target.closest('button[class*="flex items-center justify-between w-48"]');
  const isDropdownItem = target.closest('.absolute');
  
  if (!isEnterpriseButton && !isDropdownItem) {
    this.showEnterpriseDropdown = false;
  }
},
    // 阻止点击事件冒泡
    preventClose(event) {
      event.stopPropagation();
    },
    changePeriod(period) {
      this.currentPeriod = period;
      // 根据选择的周期更新图表数据
      this.updateUsageTrendChartData();
    },
    changeCompanyPeriod(period) {
      this.currentCompanyPeriod = period;
      // 根据选择的周期更新表格数据
      this.updateCompanyUsageData();
    },
    changeDataReportPeriod(period) {
      this.currentDataReportPeriod = period;
      // 根据选择的周期更新图表数据
      this.updateDataReportRateChartData();
    },
    updateUsageTrendChartData() {
      if (!this.$refs.usageTrendChart) return;
      // 销毁现有图表实例
      if (this.usageTrendChart) {
        this.usageTrendChart.dispose();
      }
      // 直接重新初始化图表，initUsageTrendChart内部已经处理了筛选逻辑
      this.initUsageTrendChart();
    },
    // 更新数据上报达标率图表数据
    updateDataReportRateChartData() {
      // 销毁现有图表实例
      if (this.dataReportRateChart) {
        this.dataReportRateChart.dispose();
      }
      // 重新初始化图表
      this.initDataReportRateChart();
    },
    // 显示企业详情
    async showCompanyDetail(company) {
  
  await ElMessageBox.alert(
    `企业名称: ${company.name}<br>企业ID: ${company.id}<br>用户总数: ${company.userCount}<br>活跃用户数: ${company.activeUsers}`,
    '企业详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  );
},
    // 分析企业数据
    async analyzeCompany(company) {
  
  await ElMessageBox.alert(
    `开始分析企业: ${company.name}<br>功能覆盖率: ${company.functionCoverage}<br>数据上报率: ${company.dataReportRate}<br>应用评分: ${company.score}`,
    '企业分析',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  );
},
    // 更新企业应用对比数据
    updateCompanyUsageData() {
      // 基础数据
      const baseData = [
        {
          id: "COM-HG-001",
          name: "河钢集团",
          icon: "fas fa-industry",
          iconBg: "bg-blue-100",
          iconColor: "text-blue-600",
          userCount: 245,
          activeUsers: 186,
          visitFrequency: "日均 68 次",
          visitChange: "↑ 12.4%",
          functionCoverage: "92%",
          functionCoverageValue: 92,
          functionCoverageColor: "#48bb78",
          dataReportRate: "96%",
          dataReportRateValue: 96,
          dataReportRateColor: "#48bb78",
          score: 94,
          scorePercentage: 94,
          scoreColor: "text-green-600",
        },
        {
          id: "COM-BG-002",
          name: "宝钢集团",
          icon: "fas fa-industry",
          iconBg: "bg-red-100",
          iconColor: "text-red-600",
          userCount: 312,
          activeUsers: 245,
          visitFrequency: "日均 92 次",
          visitChange: "↑ 8.6%",
          functionCoverage: "88%",
          functionCoverageValue: 88,
          functionCoverageColor: "#48bb78",
          dataReportRate: "94%",
          dataReportRateValue: 94,
          dataReportRateColor: "#48bb78",
          score: 92,
          scorePercentage: 92,
          scoreColor: "text-green-600",
        },
        {
          id: "COM-SG-003",
          name: "首钢集团",
          icon: "fas fa-industry",
          iconBg: "bg-green-100",
          iconColor: "text-green-600",
          userCount: 186,
          activeUsers: 142,
          visitFrequency: "日均 56 次",
          visitChange: "↑ 15.2%",
          functionCoverage: "84%",
          functionCoverageValue: 84,
          functionCoverageColor: "#4299e1",
          dataReportRate: "92%",
          dataReportRateValue: 92,
          dataReportRateColor: "#48bb78",
          score: 88,
          scorePercentage: 88,
          scoreColor: "text-green-600",
        },
        {
          id: "COM-MG-004",
          name: "鞍钢集团",
          icon: "fas fa-industry",
          iconBg: "bg-purple-100",
          iconColor: "text-purple-600",
          userCount: 156,
          activeUsers: 108,
          visitFrequency: "日均 42 次",
          visitChange: "↑ 6.8%",
          functionCoverage: "78%",
          functionCoverageValue: 78,
          functionCoverageColor: "#4299e1",
          dataReportRate: "88%",
          dataReportRateValue: 88,
          dataReportRateColor: "#4299e1",
          score: 82,
          scorePercentage: 82,
          scoreColor: "text-blue-600",
        },
        {
          id: "COM-WG-005",
          name: "武钢集团",
          icon: "fas fa-industry",
          iconBg: "bg-yellow-100",
          iconColor: "text-yellow-600",
          userCount: 128,
          activeUsers: 86,
          visitFrequency: "日均 35 次",
          visitChange: "↑ 4.2%",
          functionCoverage: "72%",
          functionCoverageValue: 72,
          functionCoverageColor: "#ecc94b",
          dataReportRate: "85%",
          dataReportRateValue: 85,
          dataReportRateColor: "#4299e1",
          score: 78,
          scorePercentage: 78,
          scoreColor: "text-blue-600",
        },
        {
          id: "COM-MG-006",
          name: "马钢集团",
          icon: "fas fa-industry",
          iconBg: "bg-orange-100",
          iconColor: "text-orange-600",
          userCount: 98,
          activeUsers: 62,
          visitFrequency: "日均 28 次",
          visitChange: "↓ 2.1%",
          functionCoverage: "65%",
          functionCoverageValue: 65,
          functionCoverageColor: "#ecc94b",
          dataReportRate: "78%",
          dataReportRateValue: 78,
          dataReportRateColor: "#ecc94b",
          score: 72,
          scorePercentage: 72,
          scoreColor: "text-yellow-600",
        },
      ];

      // 根据筛选条件过滤数据
      let filteredData = this.filterCompanyData(baseData);

      // 根据周期调整数据
      switch (this.currentCompanyPeriod) {
        case "month":
          this.companyUsageData = filteredData;
          break;
        case "quarter":
          this.companyUsageData = filteredData.map((company) => {
            return {
              ...company,
              userCount: Math.round(company.userCount * 3.2),
              activeUsers: Math.round(company.activeUsers * 3.1),
              visitFrequency: company.visitFrequency.replace(
                /日均 (\d+) 次/,
                (match, p1) => {
                  return `日均 ${Math.round(parseInt(p1) * 3.1)} 次`;
                }
              ),
            };
          });
          break;
        case "year":
          this.companyUsageData = filteredData.map((company) => {
            return {
              ...company,
              userCount: Math.round(company.userCount * 12.5),
              activeUsers: Math.round(company.activeUsers * 12.2),
              visitFrequency: company.visitFrequency.replace(
                /日均 (\d+) 次/,
                (match, p1) => {
                  return `日均 ${Math.round(parseInt(p1) * 12.2)} 次`;
                }
              ),
            };
          });
          break;
        default:
          this.companyUsageData = filteredData;
      }
    },
    initUsageTrendChart() {
      if (!this.$refs.usageTrendChart) return;
      // 保存图表实例引用
      this.usageTrendChart = echarts.init(this.$refs.usageTrendChart);
      const chart = this.usageTrendChart;

      // 根据周期生成不同的数据
      let xAxisData = [];
      let visitData = [];
      let userData = [];
      let xAxisInterval = 0; // 控制x轴标签显示间隔

      // 基础数据
      const baseData = {
        week: {
          xAxisData: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
          visitData: [1250, 1386, 1412, 1398, 1542, 1886, 1632],
          userData: [586, 602, 618, 612, 732, 848, 762],
        },
        month: {
          xAxisData: [
            "1日",
            "2日",
            "3日",
            "4日",
            "5日",
            "6日",
            "7日",
            "8日",
            "9日",
            "10日",
            "11日",
            "12日",
            "13日",
            "14日",
            "15日",
            "16日",
            "17日",
            "18日",
            "19日",
            "20日",
            "21日",
            "22日",
            "23日",
            "24日",
            "25日",
            "26日",
            "27日",
            "28日",
            "29日",
            "30日",
          ],
          visitData: [
            2450, 2486, 2512, 2498, 2542, 2586, 2632, 2678, 2642, 2698, 2732,
            2768, 2786, 2812, 2798, 2842, 2876, 2842, 2898, 2932, 2968, 2986,
            3012, 2998, 3042, 3086, 3132, 3098, 3142, 3186,
          ],
          userData: [
            1086, 1102, 1118, 1112, 1132, 1148, 1162, 1178, 1168, 1186, 1198,
            1212, 1218, 1226, 1222, 1238, 1252, 1242, 1258, 1272, 1286, 1292,
            1302, 1298, 1312, 1326, 1338, 1328, 1342, 1356,
          ],
        },
        year: {
          xAxisData: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          visitData: [
            28450, 29260, 31520, 30860, 33420, 35860, 36320, 36780, 35420,
            36980, 37320, 37860,
          ],
          userData: [
            12860, 13020, 14180, 13120, 15320, 16480, 16620, 16780, 15680,
            16860, 16980, 17560,
          ],
        },
      };

      // 如果有自定义时间范围，则生成基于日期的数据
      if (this.startDate && this.endDate) {
        // 生成日期范围内的数据
        xAxisData = this.generateDateRange(this.startDate, this.endDate);
        // 根据日期范围长度决定数据点数量
        const dataPoints = xAxisData.length;
        visitData = this.generateRandomData(dataPoints, 1000, 4000);
        userData = this.generateRandomData(dataPoints, 500, 2000);
      } else {
        // 获取基础数据
        const periodData = baseData[this.currentPeriod];
        xAxisData = [...periodData.xAxisData];
        visitData = [...periodData.visitData];
        userData = [...periodData.userData];
      }

      // 根据筛选条件调整数据
      // 1. 企业筛选
      if (this.selectedEnterprise !== "全部企业") {
        // 如果是特定企业，数据量相应减少
        const scaleFactor = this.getEnterpriseScaleFactor(
          this.selectedEnterprise
        );
        visitData = visitData.map((value) => Math.round(value * scaleFactor));
        userData = userData.map((value) => Math.round(value * scaleFactor));
      }

      // 设置x轴标签间隔
      if (xAxisData.length > 30) {
        xAxisInterval = Math.floor(xAxisData.length / 15); // 确保最多显示15个标签
      } else if (xAxisData.length > 7) {
        xAxisInterval = Math.floor(xAxisData.length / 7); // 确保最多显示7个标签
      } else {
        xAxisInterval = 0; // 显示所有标签
      }

      const option = {
        animation: false,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (params) => {
            let result = `${params[0].axisValue}<br/>`;
            params.forEach((param) => {
              const value = param.value;
              const seriesName = param.seriesName;
              // 根据筛选条件显示不同的单位提示
              if (this.selectedEnterprise !== "全部企业") {
                result += `${seriesName}: ${value.toLocaleString()} (${
                  this.selectedEnterprise
                })<br/>`;
              } else {
                result += `${seriesName}: ${value.toLocaleString()}<br/>`;
              }
            });
            return result;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "18%",
          top: "10%",
          containLabel: true,
        },
        legend: {
          data: ["访问量", "活跃用户"],
          bottom: 10,
        },
        xAxis: [
          {
            type: "category",
            data: xAxisData,
            axisLine: {
              lineStyle: {
                color: "#e2e8f0",
              },
            },
            axisLabel: {
              color: "#718096",
              fontSize: 10,
              interval: xAxisInterval, // 使用动态间隔
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "访问量",
            min: 0,
            axisLabel: {
              formatter: "{value}",
              color: "#718096",
            },
            axisLine: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: "#e2e8f0",
              },
            },
          },
          {
            type: "value",
            name: "活跃用户",
            min: 0,
            axisLabel: {
              formatter: "{value}",
              color: "#718096",
            },
            axisLine: {
              show: false,
            },
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: "访问量",
            type: "bar",
            barWidth: 10,
            itemStyle: {
              color: "#4299e1",
            },
            data: visitData,
          },
          {
            name: "活跃用户",
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            lineStyle: {
              width: 3,
              color: "#48bb78",
            },
            symbol: "circle",
            symbolSize: 8,
            itemStyle: {
              color: "#48bb78",
            },
            data: userData,
          },
        ],
      };

      chart.setOption(option);
    },
    // 新增辅助方法
    getEnterpriseScaleFactor(enterprise) {
      // 根据不同企业设置不同的数据规模系数
      const scaleFactors = {
        河钢集团: 0.35,
        宝钢集团: 0.45,
        首钢集团: 0.28,
        鞍钢集团: 0.22,
        武钢集团: 0.18,
        马钢集团: 0.15,
      };
      return scaleFactors[enterprise] || 0.3;
    },

    // 计算日期调整系数
    calculateDateAdjustment() {
      if (!this.startDate && !this.endDate) return 1;

      // 简单的日期范围调整逻辑
      // 在实际应用中，这里应该根据具体的日期范围查询真实数据
      const start = this.startDate ? new Date(this.startDate) : null;
      const end = this.endDate ? new Date(this.endDate) : null;

      if (start && end) {
        const diffTime = Math.abs(end - start);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        // 根据选择的时间范围长度调整数据
        if (diffDays <= 7) return 0.4; // 一周内
        if (diffDays <= 30) return 0.7; // 一月内
        if (diffDays <= 90) return 0.85; // 一季度内
      }

      return 1;
    },
     // 生成日期范围数组
    generateDateRange(startDate, endDate) {
      const dates = [];
      const current = new Date(startDate);
      const end = new Date(endDate);
      
      // 确保结束日期包含在范围内
      end.setDate(end.getDate() + 1);
      
      while (current < end) {
        const year = current.getFullYear();
        const month = String(current.getMonth() + 1).padStart(2, '0');
        const day = String(current.getDate()).padStart(2, '0');
        dates.push(`${year}-${month}-${day}`);
        current.setDate(current.getDate() + 1);
      }
      
      // 如果日期太多，进行抽样以避免图表过于拥挤
      if (dates.length > 30) {
        const sampledDates = [];
        const step = Math.ceil(dates.length / 30);
        for (let i = 0; i < dates.length; i += step) {
          sampledDates.push(dates[i]);
        }
        return sampledDates;
      }
      
      return dates;
    },
    // 生成随机数据
    generateRandomData(length, min, max) {
      return Array.from({ length }, () => 
        Math.floor(Math.random() * (max - min + 1)) + min
      );
    },
    initFunctionUsageChart() {
      if (!this.$refs.functionUsageChart) return;
      const chart = echarts.init(this.$refs.functionUsageChart);

      // 基础数据
      let chartData = [
        { value: 28, name: "实时监测", itemStyle: { color: "#4299e1" } },
        { value: 22, name: "风险预警", itemStyle: { color: "#f56565" } },
        { value: 18, name: "数据分析", itemStyle: { color: "#48bb78" } },
        { value: 14, name: "巡检管理", itemStyle: { color: "#9f7aea" } },
        { value: 10, name: "报表生成", itemStyle: { color: "#ecc94b" } },
        { value: 8, name: "故障处理", itemStyle: { color: "#ed8936" } },
        { value: 5, name: "其他功能", itemStyle: { color: "#a0aec0" } },
      ];

      // 根据筛选条件调整数据
      if (this.selectedEnterprise !== "全部企业") {
        const scaleFactor = this.getEnterpriseScaleFactor(
          this.selectedEnterprise
        );
        chartData = chartData.map((item) => ({
          ...item,
          value: Math.round(item.value * scaleFactor),
        }));
      }

      const option = {
        animation: false,
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            const value = params.value;
            const name = params.name;
            const percent = params.percent;
            if (this.selectedEnterprise !== "全部企业") {
              return `${name}<br/>使用次数: ${value} (${this.selectedEnterprise})<br/>占比: ${percent}%`;
            } else {
              return `${name}<br/>使用次数: ${value}<br/>占比: ${percent}%`;
            }
          },
        },
        legend: {
          orient: "vertical",
          left: 10,
          top: "center",
          data: chartData.map((item) => item.name),
        },
        series: [
          {
            name: "功能使用",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["65%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: chartData,
          },
        ],
      };
      chart.setOption(option);
    },
    initUserActivityHeatmap() {
      if (!this.$refs.userActivityHeatmap) return;
      const chart = echarts.init(this.$refs.userActivityHeatmap);
      // 生成热力图数据
      const hours = [
        "00:00",
        "01:00",
        "02:00",
        "03:00",
        "04:00",
        "05:00",
        "06:00",
        "07:00",
        "08:00",
        "09:00",
        "10:00",
        "11:00",
        "12:00",
        "13:00",
        "14:00",
        "15:00",
        "16:00",
        "17:00",
        "18:00",
        "19:00",
        "20:00",
        "21:00",
        "22:00",
        "23:00",
      ];
      const days = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
      const data = [];
      for (let i = 0; i < 7; i++) {
        for (let j = 0; j < 24; j++) {
          let value = 0;
          // 工作日工作时间活跃度高
          if (i < 5 && j >= 8 && j <= 18) {
            value = Math.round(Math.random() * 50 + 50);
          }
          // 工作日非工作时间活跃度中等
          else if (i < 5) {
            value = Math.round(Math.random() * 30 + 10);
          }
          // 周末活跃度低
          else {
            value = Math.round(Math.random() * 20 + 5);
          }
          data.push([j, i, value]);
        }
      }
      const option = {
        animation: false,
        tooltip: {
          position: "top",
          formatter: function (params) {
            return `${days[params.value[1]]} ${
              hours[params.value[0]]
            }<br>活跃度: ${params.value[2]}`;
          },
        },
        grid: {
          top: "10%",
          left: "3%",
          right: "10%",
          bottom: "20%", // 增加底部边距，为x轴标签留出空间
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: hours,
          splitArea: {
            show: true,
          },
          axisLabel: {
            fontSize: 9,
            interval: 3,
            margin: 15, // 增加标签与轴线的距离
          },
        },
        yAxis: {
          type: "category",
          data: days,
          splitArea: {
            show: true,
          },
          axisLabel: {
            margin: 15, // 增加标签与轴线的距离
          },
        },
        visualMap: {
          min: 0,
          max: 100,
          calculable: true,
          orient: "horizontal",
          left: "center",
          bottom: "0%",
          inRange: {
            color: ["#ebedf0", "#c6e48b", "#7bc96f", "#239a3b", "#196127"],
          },
        },
        series: [
          {
            name: "用户活跃度",
            type: "heatmap",
            data: data,
            label: {
              show: false,
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      chart.setOption(option);
    },
    initUserBehaviorChart() {
      if (!this.$refs.userBehaviorChart) return;
      const chart = echarts.init(this.$refs.userBehaviorChart);
      const option = {
        animation: false,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          axisLine: {
            lineStyle: {
              color: "#e2e8f0",
            },
          },
          axisLabel: {
            color: "#718096",
            fontSize: 10,
          },
          splitLine: {
            lineStyle: {
              color: "#e2e8f0",
            },
          },
        },
        yAxis: {
          type: "category",
          data: [
            "数据查询",
            "报表导出",
            "预警处理",
            "设备监控",
            "数据录入",
            "系统配置",
            "用户管理",
          ],
          axisLine: {
            lineStyle: {
              color: "#e2e8f0",
            },
          },
          axisLabel: {
            color: "#718096",
            fontSize: 10,
          },
        },
        series: [
          {
            name: "操作次数",
            type: "bar",
            data: [
              { value: 4685, itemStyle: { color: "#4299e1" } },
              { value: 3842, itemStyle: { color: "#48bb78" } },
              { value: 2956, itemStyle: { color: "#f56565" } },
              { value: 2486, itemStyle: { color: "#9f7aea" } },
              { value: 1842, itemStyle: { color: "#ecc94b" } },
              { value: 1256, itemStyle: { color: "#ed8936" } },
              { value: 865, itemStyle: { color: "#a0aec0" } },
            ],
            label: {
              show: true,
              position: "right",
              fontSize: 10,
              color: "#718096",
            },
          },
        ],
      };
      chart.setOption(option);
    },
    initAvgUsageTimeChart() {
      if (!this.$refs.avgUsageTimeChart) return;
      const chart = echarts.init(this.$refs.avgUsageTimeChart);
      const option = {
        animation: false,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: [
            "1日",
            "2日",
            "3日",
            "4日",
            "5日",
            "6日",
            "7日",
            "8日",
            "9日",
            "10日",
            "11日",
            "12日",
            "13日",
            "14日",
            "15日",
            "16日",
            "17日",
            "18日",
            "19日",
            "20日",
            "21日",
            "22日",
            "23日",
            "24日",
            "25日",
            "26日",
            "27日",
            "28日",
            "29日",
            "30日",
          ],
          axisLine: {
            lineStyle: {
              color: "#e2e8f0",
            },
          },
          axisLabel: {
            color: "#718096",
            fontSize: 10,
            interval: 4,
          },
        },
        yAxis: {
          type: "value",
          name: "分钟",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#718096",
            fontSize: 10,
          },
          splitLine: {
            lineStyle: {
              color: "#e2e8f0",
            },
          },
        },
        series: [
          {
            name: "平均使用时长",
            type: "line",
            smooth: true,
            lineStyle: {
              width: 3,
              color: "#9f7aea",
            },
            symbol: "circle",
            symbolSize: 8,
            itemStyle: {
              color: "#9f7aea",
            },
            areaStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(159, 122, 234, 0.3)",
                  },
                  {
                    offset: 1,
                    color: "rgba(159, 122, 234, 0.1)",
                  },
                ],
              },
            },
            data: [
              38.5, 39.2, 40.6, 39.8, 41.2, 42.5, 43.8, 44.2, 43.6, 44.8, 45.2,
              46.1, 46.8, 47.2, 46.5, 47.8, 48.2, 47.6, 48.8, 49.2, 49.8, 50.2,
              50.8, 50.2, 51.5, 52.2, 52.8, 52.2, 53.5, 54.2,
            ],
          },
        ],
      };
      chart.setOption(option);
    },
    initDataReportRateChart() {
      if (!this.$refs.dataReportRateChart) return;
      // 保存图表实例引用
      this.dataReportRateChart = echarts.init(this.$refs.dataReportRateChart);
      const chart = this.dataReportRateChart;

      // 根据周期生成不同的数据
      let xAxisData = [];
      let reportRateData = [];
      let xAxisInterval = 0; // 控制x轴标签显示间隔

      switch (this.currentDataReportPeriod) {
        case "week":
          xAxisData = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
          reportRateData = [92.5, 93.2, 94.6, 93.8, 95.2, 96.5, 94.8];
          xAxisInterval = 0; // 显示所有标签
          break;
        case "month":
          xAxisData = [
            "1日",
            "2日",
            "3日",
            "4日",
            "5日",
            "6日",
            "7日",
            "8日",
            "9日",
            "10日",
            "11日",
            "12日",
            "13日",
            "14日",
            "15日",
            "16日",
            "17日",
            "18日",
            "19日",
            "20日",
            "21日",
            "22日",
            "23日",
            "24日",
            "25日",
            "26日",
            "27日",
            "28日",
            "29日",
            "30日",
          ];
          reportRateData = [
            88.5, 89.2, 90.6, 89.8, 91.2, 92.5, 93.8, 94.2, 93.6, 94.8, 95.2,
            96.1, 96.8, 97.2, 96.5, 97.8, 98.2, 97.6, 98.8, 99.2, 98.8, 97.2,
            96.8, 95.2, 94.5, 93.2, 92.8, 93.2, 94.5, 95.2,
          ];
          xAxisInterval = 4; // 每隔4个显示一个标签，避免拥挤
          break;
        case "year":
          xAxisData = [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ];
          reportRateData = [
            90.5, 91.2, 92.6, 91.8, 93.2, 94.5, 95.8, 96.2, 95.6, 96.8, 97.2,
            97.8,
          ];
          xAxisInterval = 0; // 显示所有标签
          break;
      }

      const option = {
        animation: false,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: "#e2e8f0",
            },
          },
          axisLabel: {
            color: "#718096",
            fontSize: 10,
            interval: xAxisInterval, // 使用动态间隔
          },
        },
        yAxis: {
          type: "value",
          min: 70,
          max: 100,
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            formatter: "{value}%",
            color: "#718096",
            fontSize: 10,
          },
          splitLine: {
            lineStyle: {
              color: "#e2e8f0",
            },
          },
        },
        series: [
          {
            name: "数据上报达标率",
            type: "line",
            smooth: true,
            lineStyle: {
              width: 3,
              color: "#48bb78",
            },
            symbol: "circle",
            symbolSize: 8,
            itemStyle: {
              color: "#48bb78",
            },
            markLine: {
              silent: true,
              lineStyle: {
                color: "#f56565",
                type: "dashed",
              },
              data: [
                {
                  yAxis: 90,
                  label: {
                    formatter: "达标线: 90%",
                    position: "middle", //标签显示在图表内部
                    distance: [0, -20], //微调标签位置，使其更靠近线的上方
                    align: "center", //居中对齐
                  },
                },
              ],
            },
            data: reportRateData,
          },
        ],
      };
      chart.setOption(option);
    },
    initDataQualityChart() {
      if (!this.$refs.dataQualityChart) return;
      const chart = echarts.init(this.$refs.dataQualityChart);
      const option = {
        animation: false,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: 10,
          top: "center",
          data: ["优质数据", "良好数据", "一般数据", "待改进数据", "问题数据"],
        },
        series: [
          {
            name: "数据质量",
            type: "pie",
            radius: ["40%", "70%"],
            center: ["65%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: 42, name: "优质数据", itemStyle: { color: "#48bb78" } },
              { value: 28, name: "良好数据", itemStyle: { color: "#4299e1" } },
              { value: 18, name: "一般数据", itemStyle: { color: "#ecc94b" } },
              { value: 8, name: "待改进数据", itemStyle: { color: "#ed8936" } },
              { value: 4, name: "问题数据", itemStyle: { color: "#f56565" } },
            ],
          },
        ],
      };
      chart.setOption(option);
    },
  },
};
</script>
<style scoped>
/* 隐藏input number的箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
input[type="number"] {
  -moz-appearance: textfield;
}
/* 自定义颜色类 */
.bg-blue-100 {
  background-color: #ebf8ff;
}
.bg-red-100 {
  background-color: #fed7d7;
}
.bg-green-100 {
  background-color: #c6f6d5;
}
.bg-yellow-100 {
  background-color: #fefcbf;
}
.bg-purple-100 {
  background-color: #e9d8fd;
}
.bg-orange-100 {
  background-color: #feebc8;
}
.bg-teal-100 {
  background-color: #b2f5ea;
}
.bg-indigo-100 {
  background-color: #e5edff;
}
.text-blue-600 {
  color: #3182ce;
}
.text-red-600 {
  color: #e53e3e;
}
.text-green-600 {
  color: #38a169;
}
.text-yellow-600 {
  color: #d69e2e;
}
.text-purple-600 {
  color: #805ad5;
}
.text-orange-600 {
  color: #dd6b20;
}
.text-teal-600 {
  color: #319795;
}
.text-indigo-600 {
  color: #5a67d8;
}
</style>
